package com.yswee.mallnavi.model.info;


import com.yswee.framework.data.BaseArrayData;
import com.yswee.framework.data.parser.IParser;
import com.yswee.framework.net.ITaskContext;
import com.yswee.framework.net.http.Callback;
import com.yswee.framework.utils.PinYinUtils;
import com.yswee.framework.utils.StringUtils;
import com.yswee.mallnavi.context.ApiConstant;
import com.yswee.mallnavi.entity.ArrayData;
import com.yswee.mallnavi.entity.info.BrandEntity;
import com.yswee.mallnavi.model.BaseListModel;
import com.yswee.mallnavi.parser.BaseListGsonParser;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

public class BrandListModel extends BaseListModel<BrandEntity> {

	private String mCategoryId;
	private String mKeyword;
	private ArrayList<BrandEntity> mDataArray;

	public void setKeyword(String keyword) {
		mKeyword = keyword;
	}

	public void setParams(String categoryId) {
		mCategoryId = categoryId;
	}

	public ArrayList<BrandEntity> getDataArray() {
		return mDataArray;
	}

	public BrandListModel(ITaskContext context) {
		super(context);
	}

	@Override
	protected IParser<BaseArrayData<BrandEntity>> createParser() {
		return new ListParser();
	}
	
	@Override
	protected String getUrl(Callback<BaseArrayData<BrandEntity>> c, int pageIndex) {
		StringBuilder url = new StringBuilder();
		url.append(ApiConstant.API_BRAND_LIST).
			append("?BrandCategoryId=").append(mCategoryId).
			append("&filterText=").append(StringUtils.isEmpty(mKeyword) ? "" : mKeyword).
			append("&skipCount=0&maxResultCount=999");
		return url.toString();
	}

	@Override
	protected void getPageDataGet(Callback<BaseArrayData<BrandEntity>> c) {
		mDataArray = null;
		super.getPageDataGet(c);
	}

	private class ListParser extends BaseListGsonParser<BrandEntity> {
		@Override
		public BaseArrayData<BrandEntity> parseData(String json) {
			mReponseData = json;
			JSONObject jo = asJSONObject(json);
			if(jo != null) {
				mIsOk = true;
				JSONArray ja = jo.optJSONArray("items");
				if(ja != null) {
					BrandEntity t = null;
					ArrayData<BrandEntity> array = new ArrayData<BrandEntity>();
					for(int i = 0; i < ja.length(); i++) {
						try {
							JSONObject jod = ja.getJSONObject(i);
							t = parseDataT(jod.getJSONObject("brand").toString());
						} catch (Exception e) {
							e.printStackTrace();
						}
						if(t != null) {
							array.array.add(t);
						}
					}
					for (BrandEntity contact : array.getArray()) {
						contact.pinyin = PinYinUtils.cn2py(contact.name);
						contact.key = StringUtils.getAlpha(contact.pinyin);
						contact.isGroup = false;
					}
					mDataArray = new ArrayList<BrandEntity>();
					for (BrandEntity contact : array.getArray()) {
						mDataArray.add(contact);
					}
					return array;
				}
			} else {
				mIsOk = false;
			}
			return null;
		}
	}

}
